import { api } from "src/boot/axios";
import { Notify } from "quasar";
import { isLogin } from "./common.js";

// 获取统一的请求头
const getHeaders = () => ({
  ApiKey: btoa(
    `${localStorage.getItem("token") || ""}` +
      "$$" +
      `${localStorage.getItem("email") || ""}`
  ),
});

// 解析错误信息的辅助函数
const parseErrorMessage = (error) => {
  if (error.response?.data) {
    const { error: errorMsg, message, msg } = error.response.data;
    return errorMsg || message || msg || "请求失败";
  }
  return error.message || "网络错误";
};

// 处理路径的辅助函数
const processPath = (path) => {
  return path.replace(/^cloud\/[^/]+\//, ""); // 删除前缀cloud/userinfo.id
};

// 显示错误通知的辅助函数
const showErrorNotify = (error, defaultMessage) => {
  const message = parseErrorMessage(error);
  Notify.create({
    type: "negative",
    message: message || defaultMessage,
    position: "top",
    timeout: 3000,
  });
};

// 显示成功通知的辅助函数
const showSuccessNotify = (message) => {
  Notify.create({
    type: "positive",
    message: message,
    position: "top",
    timeout: 3000,
  });
};

// 处理错误状态码的辅助函数
const handleErrorStatus = (error) => {
  if (error.response?.status === 401 || error.response?.status === 403) {
    isLogin.value = false;
    localStorage.removeItem("token");
    localStorage.removeItem("email");
  }
};

// 获取播放列表
export const getPlaylist = async () => {
  try {
    const response = await api.get("/api/v1/music", {
      headers: getHeaders(),
    });
    return response.data;
  } catch (error) {
    console.error("获取播放列表失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "获取播放列表失败");
    throw error;
  }
};

// ==================== 云存储 API 函数 ====================

// 浏览目录
export const browseDirectory = async (path = "/") => {
  try {
    const response = await api.get("/api/v1/cloud", {
      params: { path },
      headers: getHeaders(),
    });

    return response.data;
  } catch (error) {
    console.error("浏览目录失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "浏览目录失败");
    throw error;
  }
};

// 获取文件下载信息
export const getDownloadInfo = async (path) => {
  try {
    const response = await api.get("/api/v1/cloud", {
      params: {
        path: processPath(path),
        action: "download", // 指定下载动作
      },
      headers: getHeaders(),
    });
    return response.data;
  } catch (error) {
    console.error("获取下载信息失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "获取下载信息失败");
    throw error;
  }
};

// 下载文件（通过URL）
export const downloadFileFromUrl = async (downloadUrl, filename) => {
  try {
    const response = await fetch(downloadUrl);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.blob();
  } catch (error) {
    console.error("从URL下载文件失败:", error);
    throw error;
  }
};

// 上传文件
export const uploadFile = async (
  path,
  name,
  fileContent,
  showSuccess = true
) => {
  try {
    const response = await api.post(
      "/api/v1/cloud",
      {
        action: "upload_file",
        path,
        name,
        file_content: fileContent,
      },
      {
        headers: getHeaders(),
      }
    );

    if (showSuccess) {
      showSuccessNotify("文件上传成功");
    }
    return response.data;
  } catch (error) {
    console.error("上传文件失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "上传文件失败");
    throw error;
  }
};

// 创建目录
export const createDirectory = async (path, name, showSuccess = true) => {
  try {
    const response = await api.post(
      "/api/v1/cloud",
      {
        action: "create_dir",
        path,
        name,
      },
      {
        headers: getHeaders(),
      }
    );

    if (showSuccess) {
      showSuccessNotify("目录创建成功");
    }
    return response.data;
  } catch (error) {
    console.error("创建目录失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "创建目录失败");
    throw error;
  }
};

// 重命名文件或目录
export const renameItem = async (oldPath, newPath, showSuccess = true) => {
  try {
    const response = await api.put(
      "/api/v1/cloud",
      {
        action: "rename",
        old_path: processPath(oldPath),
        new_path: processPath(newPath),
      },
      {
        headers: getHeaders(),
      }
    );

    if (showSuccess) {
      showSuccessNotify("重命名成功");
    }
    return response.data;
  } catch (error) {
    console.error("重命名失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "重命名失败");
    throw error;
  }
};

// 删除文件或目录
export const deleteItem = async (path, showSuccess = true) => {
  try {
    const response = await api.delete("/api/v1/cloud", {
      data: {
        action: "delete",
        path: processPath(path),
      },
      headers: getHeaders(),
    });

    if (showSuccess) {
      showSuccessNotify("删除成功");
    }
    return response.data;
  } catch (error) {
    console.error("删除失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "删除失败");
    throw error;
  }
};

// 文件类型判断辅助函数
export const isTextFile = (filename) => {
  const textExtensions = [
    ".txt",
    ".md",
    ".json",
    ".xml",
    ".csv",
    ".ini",
    ".conf",
    ".log",
    ".py",
    ".js",
    ".html",
    ".css",
    ".java",
    ".cpp",
    ".c",
    ".php",
    ".rb",
    ".go",
    ".rs",
    ".sh",
    ".bat",
    ".ps1",
  ];
  const lastDotIndex = filename.lastIndexOf(".");
  if (lastDotIndex === -1 || lastDotIndex === 0) {
    return false; // 没有扩展名或文件名以点开头
  }
  const ext = filename.toLowerCase().substring(lastDotIndex);
  return textExtensions.includes(ext);
};

export const isBinaryFile = (filename) => {
  const binaryExtensions = [
    // 图片
    ".jpg",
    ".jpeg",
    ".png",
    ".gif",
    ".bmp",
    ".webp",
    ".svg",
    ".ico",
    ".tiff",
    ".tif",
    ".heic",
    ".heif",
    // 音频
    ".mp3",
    ".wav",
    ".flac",
    ".aac",
    ".ogg",
    ".m4a",
    ".wma",
    // 视频
    ".mp4",
    ".avi",
    ".mov",
    ".wmv",
    ".flv",
    ".mkv",
    ".webm",
    ".m4v",
    ".3gp",
    // 文档
    ".pdf",
    ".doc",
    ".docx",
    ".xls",
    ".xlsx",
    ".ppt",
    ".pptx",
    // 压缩
    ".zip",
    ".rar",
    ".7z",
    ".tar",
    ".gz",
    ".bz2",
  ];
  const lastDotIndex = filename.lastIndexOf(".");
  if (lastDotIndex === -1 || lastDotIndex === 0) {
    return false; // 没有扩展名或文件名以点开头
  }
  const ext = filename.toLowerCase().substring(lastDotIndex);
  return binaryExtensions.includes(ext);
};

// 文件上传辅助函数 - 处理不同类型的文件
export const uploadFileWithType = async (path, file, showSuccess = true) => {
  try {
    let fileContent;

    console.log(
      "正在处理文件:",
      file.name,
      "大小:",
      file.size,
      "类型:",
      file.type
    );

    if (isTextFile(file.name)) {
      console.log("识别为文本文件:", file.name);
      // 文本文件直接读取内容
      fileContent = await file.text();
    } else if (isBinaryFile(file.name)) {
      console.log("识别为二进制文件:", file.name);
      // 二进制文件转换为base64 - 使用更高效的方法
      const base64 = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = () => {
          // 移除data:application/octet-stream;base64,前缀
          const base64String = reader.result.split(",")[1];
          resolve(base64String);
        };
        reader.readAsDataURL(file);
      });

      fileContent = base64;
    } else {
      console.log(
        "未知文件类型，按二进制文件处理:",
        file.name,
        "文件类型:",
        file.type
      );
      // 对于未知类型的文件，也按二进制文件处理
      const base64 = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = () => {
          // 移除data:application/octet-stream;base64,前缀
          const base64String = reader.result.split(",")[1];
          resolve(base64String);
        };
        reader.readAsDataURL(file);
      });

      fileContent = base64;
    }

    return await uploadFile(path, file.name, fileContent, showSuccess);
  } catch (error) {
    console.error("文件上传处理失败:", error);
    showErrorNotify(error, "文件上传处理失败");
    throw error;
  }
};

// 离线下载文件
export const createOfflineDownload = async (
  url,
  path,
  filename,
  showSuccess = true
) => {
  try {
    const response = await api.post(
      "/api/v1/cloud",
      {
        action: "download_file",
        url: url,
        path: path,
        name: filename,
      },
      {
        headers: getHeaders(),
      }
    );

    if (showSuccess) {
      showSuccessNotify("离线下载任务已创建");
    }
    return response.data;
  } catch (error) {
    console.error("离线下载失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "离线下载失败");
    throw error;
  }
};

// 批量操作辅助函数
export const batchUpload = async (path, files, showProgress = true) => {
  const results = [];
  const total = files.length;

  for (let i = 0; i < files.length; i++) {
    const file = files[i];

    if (showProgress) {
      Notify.create({
        type: "info",
        message: `正在上传 ${file.name} (${i + 1}/${total})`,
        position: "top",
        timeout: 1000,
      });
    }

    try {
      const result = await uploadFileWithType(path, file, false);
      results.push({ success: true, file: file.name, result });
    } catch (error) {
      results.push({ success: false, file: file.name, error: error.message });
    }
  }

  const successCount = results.filter((r) => r.success).length;
  const failCount = results.length - successCount;

  if (showProgress) {
    if (failCount === 0) {
      showSuccessNotify(`批量上传完成，共 ${total} 个文件`);
    } else {
      Notify.create({
        type: "warning",
        message: `批量上传完成，成功 ${successCount} 个，失败 ${failCount} 个`,
        position: "top",
        timeout: 3000,
      });
    }
  }

  return results;
};

// ==================== 图床 API 函数 ====================

// 获取图床配置信息
export const getImageHostConfig = async (path) => {
  try {
    const response = await api.get("/cloudImage", {
      params: { path: processPath(path) },
      headers: getHeaders(),
    });
    return response.data;
  } catch (error) {
    console.error("获取图床配置失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "获取图床配置失败");
    throw error;
  }
};

// 启用图床功能
export const enableImageHost = async (path) => {
  try {
    const response = await api.post("/cloudImage", null, {
      params: { path: processPath(path) },
      headers: getHeaders(),
    });
    showSuccessNotify("图床功能启用成功");
    return response.data;
  } catch (error) {
    console.error("启用图床功能失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "启用图床功能失败");
    throw error;
  }
};

// 取消图床功能
export const disableImageHost = async (path) => {
  try {
    const response = await api.delete("/cloudImage", {
      params: { path: processPath(path) },
      headers: getHeaders(),
    });
    showSuccessNotify("图床功能已取消");
    return response.data;
  } catch (error) {
    console.error("取消图床功能失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "取消图床功能失败");
    throw error;
  }
};

// 刷新图床Token
export const refreshImageHostToken = async (path) => {
  try {
    const response = await api.put("/cloudImage", null, {
      params: { path: processPath(path) },
      headers: getHeaders(),
    });
    showSuccessNotify("Token刷新成功");
    return response.data;
  } catch (error) {
    console.error("刷新Token失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "刷新Token失败");
    throw error;
  }
};

// 上传图片到图床
export const uploadImageToHost = async (path, imageFile) => {
  try {
    const formData = new FormData();
    formData.append("image", imageFile);

    const response = await api.post("/cloudImage", formData, {
      params: { path: processPath(path) },
      headers: {
        ...getHeaders(),
        "Content-Type": "multipart/form-data",
      },
    });
    return response.data;
  } catch (error) {
    console.error("上传图片失败:", error);
    handleErrorStatus(error);
    showErrorNotify(error, "上传图片失败");
    throw error;
  }
};
